package com.money.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.money.common.constant.SearchConstant;
import com.money.common.dto.es.SkuEsModel;
import com.money.search.config.ElasticConfig;
import com.money.search.service.EsSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class EsSaveServiceImpl implements EsSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveSkusToEs(List<SkuEsModel> models) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        ObjectMapper jsonTool = new ObjectMapper();
        for (SkuEsModel model : models) {
            //指定保存的索引
            IndexRequest indexRequest = new IndexRequest(SearchConstant.PRODUCT_INDEX);
            //设置索引id
            indexRequest.id(model.getSkuId().toString());
            String json = jsonTool.writeValueAsString(model);
            //设置索引数据
            indexRequest.source(json, XContentType.JSON);
            //将其保存到批量工具中
            bulkRequest.add(indexRequest);
        }
        //统一发送给es进行保存
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        boolean result = bulkResponse.hasFailures();
        if(result){
            log.error("商品保存到es中发生错误");
        }
        return result;
    }
}
